// pages/category/category.js
import { request } from "../../request/request"


Page({

  /**
   * 页面的初始数据
   */
  data: {
    leftMenuList: [],
    rightMenuList: [],
    currendIndex: 0,
    scrollTop: 0
  },

  categoryData: [],
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // 获取本地存储
    const Cates = wx.getStorageSync('cates');
    if (!Cates) {
      this.getCategoryList();
    } else {
      //  判断是否超过10秒
      if (Date.now() - Cates.time > 1000 * 10) {
        this.getCategoryList();
      } else {
        this.categoryData = Cates;
        let leftMenuList = this.categoryData.map(v => v.cat_name);
        let rightMenuList = this.categoryData[0].children
        this.setData({
          leftMenuList,
          rightMenuList
        })
      }
    }
  },

  getCategoryList() {
    request({ url: "/categories" }).then(res => {
      this.categoryData = res.data.message;
      // 存入本地的存储
      wx.setStorageSync('cates', { time: Date.now(), data: this.categoryData });

      let leftMenuList = this.categoryData.map(v => v.cat_name);
      let rightMenuList = this.categoryData[0].children
      this.setData({
        leftMenuList,
        rightMenuList
      })
    })
  },

  handleIndexClick(i) {
    const { index } = i.currentTarget.dataset;
    let rightMenuList = this.categoryData[index].children
    this.setData({
      rightMenuList,
      currendIndex: index,
      scrollTop: 0
    })
  }

})